package com.q.tqb.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.q.tqb.R;
import com.q.tqb.activity.grab.GrabMapActivity;
import com.q.tqb.activity.mine.ChangeLevelActivity;
import com.q.tqb.activity.mine.MineAddBusiness1Activity;
import com.q.tqb.activity.mine.MineAddBusinessActivity;
import com.q.tqb.activity.mine.MineBusinessActivity;
import com.q.tqb.activity.mine.MineCardActivity;
import com.q.tqb.activity.mine.MineDataActivity;
import com.q.tqb.activity.mine.MineRedEnvelopeActivity;
import com.q.tqb.activity.mine.MineSettingActivity;
import com.q.tqb.activity.mine.MineTweeterActivity;
import com.q.tqb.activity.mine.MineTweeterIntroActivity;
import com.q.tqb.activity.mine.MineWalletActivity;
import com.q.tqb.activity.send.SendSpeakingActivity;
import com.q.tqb.base.AppConst;
import com.q.tqb.luban.Luban;
import com.q.tqb.luban.OnCompressListener;
import com.q.tqb.model.BusinessInfo;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.MD5Util;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.ToastUtils;
import com.q.tqb.util.http.IRawResponse;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.IResponse2;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.util.oss.OssCallback;
import com.q.tqb.util.oss.OssService;
import com.q.tqb.view.GlideLoader;
import com.q.tqb.view.dialog.CustomProgressDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class MineFragment extends Fragment {
    public static final int REQUEST_CODE_SELECT = 100;

    @BindView(R.id.civ_head)
    ImageView mCivHead;
    @BindView(R.id.tv_name)
    TextView mTvName;

    @BindView(R.id.rl_setting)
    RelativeLayout mRlSetting;
    @BindView(R.id.rl_level)
    RelativeLayout mRlLevel;
    @BindView(R.id.rl_business)
    RelativeLayout rl_business;
    @BindView(R.id.rl_promote)
    RelativeLayout rl_promote;
    Unbinder unbinder;

    @BindView(R.id.tv_level)
    TextView tv_level;
    @BindView(R.id.rl_wallet)
    RelativeLayout mRlWallet;
    @BindView(R.id.rl_card)
    RelativeLayout mRlCard;
    @BindView(R.id.iv_vip)
    ImageView mIvVip;
    @BindView(R.id.tv_dl)
    TextView tv_dl;
    @BindView(R.id.tv_sq)
    TextView tv_sq;

    private int isUserAgent;
    private int uid;
    private String img = "";
    protected CustomProgressDialog mProgressDialog;

    public MineFragment() {
    }


    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        unbinder = ButterKnife.bind(this, view);
        isUserAgent = (int) SPUtil.get(getActivity(), "isUserAgent", 0);
        uid = (int) SPUtil.get(getActivity(), "uid", 0);
        mProgressDialog = new CustomProgressDialog(getActivity());
        initImagePicker();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        init();
    }

    private void init() {

        String headImg = SPUtil.getString(getActivity(), "header");
        String nickname = SPUtil.getString(getActivity(), "nickname");
        String level_name = SPUtil.getString(getActivity(), "level_name");
        String level = SPUtil.getString(getActivity(), "level");
        String agent_name = SPUtil.getString(getActivity(), "agent_name");
        int is_community = (int) SPUtil.get(getActivity(), "is_community", 0);
        isUserAgent = (int) SPUtil.get(getActivity(), "isUserAgent", 0);

        if (isUserAgent == 1) {
            mIvVip.setVisibility(View.VISIBLE);
        } else {
            mIvVip.setVisibility(View.GONE);
        }


        Glide
                .with(getActivity())
                .load(headImg)
                .error(R.drawable.ic_head)
                .placeholder(R.drawable.ic_head)
                .dontAnimate()
                .into(mCivHead);

        if (!TextUtils.isEmpty(level_name)) {
            tv_level.setText("LV" + level + ":" + level_name);
        }
        if (!TextUtils.isEmpty(agent_name)) {
            tv_dl.setText(getString(R.string.txt_dl, agent_name));
            rl_business.setVisibility(View.VISIBLE);
        } else {
            tv_dl.setText("您还不是代理");
            rl_business.setVisibility(View.GONE);
        }
        if (is_community == 1) {
            tv_sq.setText(getString(R.string.txt_sq, uid + ""));
            rl_promote.setVisibility(View.VISIBLE);
        }else {
            tv_sq.setText("您还没加入社区");
            rl_promote.setVisibility(View.GONE);
        }
        mTvName.setText(nickname);
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideLoader());
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setSelectLimit(9);
    }

    private void getBusinessData() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));

        OkHttpUtil.getInstance().post(getActivity(), AppConst.URL_GET_MERCHANT, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                Intent intent;
                if (TextUtils.isEmpty(result)) {
                    intent = new Intent(getActivity(), MineAddBusiness1Activity.class);
                    startActivityForResult(intent, 54);
                } else {
                    BusinessInfo businessInfo = gson.fromJson(result, BusinessInfo.class);
                    int status = businessInfo.getStatus();
                    if (status == 0) {
                        intent = new Intent(getActivity(), MineAddBusiness1Activity.class);
                        startActivityForResult(intent, 54);
                    } else if (status == 1) {
                        Toast.makeText(getActivity(), R.string.mine_store_review, Toast.LENGTH_SHORT).show();
                    } else {
                        intent = new Intent(getActivity(), MineBusinessActivity.class);
                        startActivity(intent);
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                if (statusCode == 400) {
                    Intent intent = new Intent(getActivity(), MineAddBusiness1Activity.class);
                    startActivityForResult(intent, 54);
                } else {
                    Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                }


            }
        });
    }


    @OnClick({R.id.rl_wallet, R.id.rl_setting, R.id.rl_level, R.id.rl_card,
            R.id.rl_red, R.id.civ_head, R.id.rl_call, R.id.tv_chang_level})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.rl_wallet:
                //  intent = new Intent(getActivity(), GrabImageActivity.class);
                intent = new Intent(getActivity(), MineWalletActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_card:
                intent = new Intent(getActivity(), MineCardActivity.class);
                startActivity(intent);
                break;
            case R.id.civ_head:
//                intent = new Intent(getActivity(), MineDataActivity.class);
//                startActivityForResult(intent, 53);
                selectDialog();
                break;
            case R.id.rl_red:
                intent = new Intent(getActivity(), MineRedEnvelopeActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_setting:
                intent = new Intent(getActivity(), MineSettingActivity.class);
                startActivityForResult(intent, 52);
                break;
            case R.id.rl_level:
                Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.rl_promote:
                isUserAgent = (int) SPUtil.get(getActivity(), "isUserAgent", 0);
                if (isUserAgent == 1) {
                    intent = new Intent(getActivity(), MineTweeterActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(getActivity(), MineTweeterIntroActivity.class);
                    startActivityForResult(intent, 55);
                }
                break;
            case R.id.rl_business:
//                getBusinessData();
                break;
            case R.id.rl_call:
                callTel();
                break;
            case R.id.tv_chang_level:
                intent = new Intent(getActivity(), ChangeLevelActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void callTel() {
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(getActivity());
        normalDialog.setTitle("温馨提示");
        normalDialog.setMessage("是否拨打电话15112686816?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:15112686816"));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
        normalDialog.setNegativeButton("取消", null);
        // 显示
        normalDialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 55 && resultCode == Activity.RESULT_OK) {
            isUserAgent = 1;
            Intent intent1 = new Intent(getActivity(), MineTweeterActivity.class);
            startActivity(intent1);
        }
        if (requestCode == 52 && resultCode == Activity.RESULT_OK) {
            getActivity().finish();
        }
        if (requestCode == 53 && resultCode == Activity.RESULT_OK) {
            init();
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> selImageList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (selImageList != null) {
                    compressImage(selImageList.get(0));
                }
            }
        }
    }

    private void selectDialog() {
        final String[] items = {"相机拍照", "相册选择"};
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(getActivity());
        singleChoiceDialog.setTitle("选择方式");
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            ImagePicker.getInstance().setSelectLimit(1);
                            Intent intent = new Intent(getContext(), ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            startActivityForResult(intent, REQUEST_CODE_SELECT);
                        } else {
                            ImagePicker.getInstance().setSelectLimit(1);
                            Intent intent1 = new Intent(getContext(), ImageGridActivity.class);
                            startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        }
                        dialog.dismiss();
                    }
                });
        singleChoiceDialog.show();
    }

    private void compressImage(final ImageItem imageItem) {
        mProgressDialog.show();
        String path = Environment.getExternalStorageDirectory() + "/tqb/tqb_" + System.currentTimeMillis() + ".jpg";
        String upPointName = "image/" + uid + "_" + System.currentTimeMillis() + ".JPEG";
        imageItem.setCompressName(path);
        imageItem.setUpName(upPointName);
        Luban.with(getContext())
                // 传人要压缩的图片列表
                .load(imageItem.path)
                // 忽略不压缩图片的大小
                .setTargetDir(path)
                //设置回调
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        uPImage(imageItem);
                        LogUtil.i("file.getPath()" + file.getPath());
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.getInstanc(getActivity()).showToast("压缩图片出错，请重新选择图片");
                        mProgressDialog.dismiss();
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩


    }


    private void uPImage(final ImageItem imageItem) {

        OssService.asyncPutFile(imageItem.getUpName(), imageItem.getCompressName(), new OssCallback(new Handler(), new IRawResponse() {
            @Override
            public void onSuccess(String response) {
                Log.e("test", response);
                img = String.format("%s%s", img, AppConst.OSS_URL + imageItem.getUpName());
                if (!TextUtils.isEmpty(img))
                    modifyImg(img);
            }

            @Override
            public void onFailure(String errorMsg) {
//                showToast("请检查您的网络");
//                imageAmount = 0;
                LogUtil.i(errorMsg);
                mProgressDialog.dismiss();
                ToastUtils.getInstanc(getActivity()).showToast(errorMsg);
            }
        }));
    }

    private void modifyImg(final String img_address) {
        int uid = (int) SPUtil.get(getActivity(), "uid", 0);
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        map.put("img_address", img_address);

        OkHttpUtil.getInstance().post2(getActivity(), AppConst.URL_CHANGE_HEADER, map, new IResponse2() {

            @Override
            public void onSuccess(JsonElement element, String msg) {
                ToastUtils.getInstanc(getActivity()).showToast(msg);
                mProgressDialog.dismiss();
                Glide
                        .with(getActivity())
                        .load(img_address)
                        .error(R.drawable.ic_head)
                        .placeholder(R.drawable.ic_head)
                        .dontAnimate()
                        .into(mCivHead);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                ToastUtils.getInstanc(getActivity()).showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });
    }
}
